<?php
/**
 *     
 *  生成订单 
 */
//require_once("IapppayCpSyncForPHP/base.php");
//require_once("alipay/config.php");
//require_once("IapppayCpSyncForPHP/base.php");
//require_once("IapppayCpSyncForPHP/config.php");

class ApplyABPay extends APIBase {
	public $tag = "ApplyABPay";
	public $isLogin = true;
	
	public function before() {
		$this->initMysql();
		return true;
	}
		
	//生成随机24位订单号
	protected function createOrderId ($length = 24) {
		$seed=md5(microtime());
		$pwd='';
		for($i=0;$i<$length;$i++){
			$pwd.=$seed{mt_rand(0,31)};
		}
		$hash=md5($pwd);
		return substr($hash,0,$length);
	}
	
	protected function paraFilter($para) {
	  $str='';	
	  foreach($para as $key=>$val){
	     if($key=='sign_type' || $key == 'sign'){
		   continue;
		  }
	   else{
	     if($str ==''){
		   $str =$key.'='.'"'.$val.'"';
	     }else{
		   $str =$str.'&'.$key.'='.'"'.$val.'"';
		 }	
		
	     }
        }
		return $str;
    }
	
    protected function argSort($para) {
		ksort($para);
		reset($para);
		return $para;
     }
    //RSA签名
    protected function sign($data) {
	
	   //读取私钥文件
	   //$sign = 111;
	   $path = dirname(__FILE__);
	   $priKey =  file_get_contents($path."/alipay/rsa_private_key.pem");//私钥文件路径
	  //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
	   $res = openssl_get_privatekey($priKey);
	  //调用openssl内置签名方法，生成签名$sign
	   openssl_sign($data, $sign, $res);
	  //释放资源 
	   openssl_free_key($res);
	   //base64编码
	   $sign = base64_encode($sign);
	   return $sign;
	 
	}


     	
	public function logic() {
		/*if (!isset($this->param['version'])) {
			$this->returnError(310, "param must be needed");
		}
*/    
		if (!isset($this->param['goodsid'])) {
			$this->returnError(310, "goodsid must be needed");
		}
		
		//支付方式 （pay_type 1,IM钱包余额 2,微信支付 3,支付宝支付）
		if (!isset($this->param['pay_type'])) {
			$this->returnError(310, "pay_type must be needed");
		}
		
        //根据id查询出商品信息
		$where['id'] = (int)$this->param['goodsid'];
		$good = $this->mysql->select('goods','*',$where);

		if(!count($good)) {     
			$this->returnError(310, "goodsid is not exists");
		}
		$payinfo['uid'] = (int) $this->uid;
		$payinfo['price'] = (float) $good[0]['buy_money'];
		$payinfo['pay_type'] = (int) $this->param['pay_type'];
		$payinfo['goodsid'] = (int) $this->param['goodsid'];
		$payinfo['version'] = 0;
		$payinfo['create_time'] = time();
		$payinfo['type'] = 0;
		$payinfo['is_send'] = 0;
		$payinfo['orderid'] = $this->createOrderId();
		$sign  = $this->mysql->insert('applypay', $payinfo);

		if ($sign) {
			if((int) $this->param['pay_type']==1){//IM钱包支付
			    $user = $this->data_redis->hMGet('hu:'.$payinfo['uid'],array('money','room_card'));
                if($user['money'] < $payinfo['price']){
					$this->returnError(302,'钱包余额不足');
				}
                $money = $user['money'] - $payinfo['price'];
				$num = $good[0]['money'];//产品数量
				
				if($good[0]['type']==1){//房卡
					$room_card = (int)$user['room_card']+$num;
					$this->data_redis->hMset('hu:'.$payinfo['uid'],array('money'=>$money,'room_card'=>$room_card));
				}
				
				//判断是否存在背包				
			    $isExists = $this->cache_redis->keys('hbackpack:'.$payinfo['uid'].":*");
				if(count($isExists) <= 0){
					//若不存在则添加背包并初始化
					$data = array('uid'=>$payinfo['uid'],'propid'=>(int)$good[0]['propid'],'count'=>$num,'createtime'=>time(),'status'=>1);
					$this->cache_redis->hMset('hbackpack:'.$payinfo['uid'].':'.(int)$good[0]['propid'],$data);
				}else{
					//若存在则判断是否存在相同道具
					$isExistsProp = $this->cache_redis->exists('hbackpack:'.$payinfo['uid'].':'.(int)$good[0]['propid']);
					//存在相同道具,则叠加
					if($isExistsProp){
						$row = $this->cache_redis->hMget('hbackpack:'.$payinfo['uid'].':'.(int)$good[0]['propid'],array('propid','count'));
						if($row['propid']==1){//房卡
						    $count = 0;
							$count = $row['count']+$num;
							$this->cache_redis->hMset('hbackpack:'.$payinfo['uid'].':'.(int)$good[0]['propid'],array('count'=>$count,'status'=>1));
						}else{//其他道具
							
						}
					}else{
					//不存在相同道具,则添加记录
					    $data = array('uid'=>$payinfo['uid'],'propid'=>(int)$good[0]['propid'],'count'=>$num,'createtime'=>time(),'status'=>1);
					    $this->cache_redis->hMset('hbackpack:'.$payinfo['uid'].':'.(int)$good[0]['propid'],$data);
					}

				}
                $this->returnData('success');
				
			}elseif((int) $this->param['pay_type']==2){//微信支付
				
				
			}elseif((int) $this->param['pay_type']==3){
				
				
			}elseif((int) $this->param['pay_type']==4){//支付宝支付
				$orderUrl = ibconfig::$orderUrl;
			    $appkey = ibconfig::$appkey;
			    $platpkey = ibconfig::$platpkey;
			    //$transid;
			    $appid = ibconfig::$appid;
				$orderReq['waresid'] = (int) $this->param['goodsid'];
                $orderReq['cporderid'] = (string)$payinfo['orderid']; //确保该参数每次 都不一样。否则下单会出问题。
                $orderReq['price'] = 0.1;   //单位：元
                $orderReq['currency'] = 'RMB';
                $orderReq['appuserid'] = (string) $this->uid;//玩家id
                $orderReq['notifyurl'] = 'http://120.76.189.164/zjgpay/iappPayTrade.php';
				//组装请求报文  对数据签名
                $reqData = ipbase::composeReq($orderReq, $appkey);
				 //发送到爱贝服务后台请求下单
                $respData = ipbase::request_by_curl($orderUrl, $reqData);
			    Config::$logger->info($this->tag, "respData:".$respData);
				//验签数据并且解析返回报文
                if(!ipbase::parseResp($respData, $platpkey, $respJson)) {
		           Config::$logger->info($this->tag, "parseResp:failed");
                }else{
					
    	        //echo "success";
    	        //echo "服务端下单完成，trasnid:<br/>";
    	        // print_r($respJson);
                // 下单成功之后获取 transid
		        Config::$logger->info($this->tag, "trasnid:success");
    	        $transid=$respJson->transid;
                }      
			$reorderinfo = array('transid'=>$transid,'appid'=>$appid);			
			$this->returnData($reorderinfo);
			}
			
		} else {
			$this->returnError(301,'create order failed!');
		}
	}
    
	public function after() {
		$this->deinitMysql();
	}
}

?>
